# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

from .. import _
import urllib2 as urllib
from xml.dom import minidom
import re
import sys

class Querier(object):

    def __init__(self):
        object.__init__(self)
        self.shortName = "leoslyrics"
        self.longName = "Leo's Lyrics"
        self.auth = "Etude"
        self.search_fmt = "http://api.leoslyrics.com/api_search.php?auth=%s&artist=%s&songtitle=%s"
        self.fetch_fmt = "http://api.leoslyrics.com/api_lyrics.php?auth=%s&hid=%s"

    def process(self, item):

        artist = urllib.quote(item.artist.encode('utf-8'))
        song_title = urllib.quote(item.song_title.encode('utf-8'))

        try:
            data = urllib.urlopen(self.search_fmt % (self.auth, artist, song_title))
            doc = minidom.parse(data)

            results = doc.getElementsByTagName('result')
        except Exception, e:
            print(sys.exc_info())
            return ''
        
        hid = ''
        for result in results:
            try:
                res_artist_node = result.getElementsByTagName('artist')[0]
                res_artist = res_artist_node.getElementsByTagName('name')[0].childNodes[0].nodeValue
                res_title = result.getElementsByTagName('title')[0].childNodes[0].nodeValue
                
                found = False
                if ((re.search(item.artist, res_artist, re.I) or 
                    re.search(res_artist, item.artist, re.I)) and 
                    (re.search(item.song_title, res_title, re.I) or
                        re.search(res_title, item.song_title, re.I))
                    ):
                    found = True
                if not found:
                    continue

                hid = result.attributes['hid'].nodeValue
                break
            except:
                print(sys.exc_info())
                return ''

        if not hid:
            return ''

        hid = urllib.quote(hid.encode('utf-8'))
        try:
            data = urllib.urlopen(self.fetch_fmt % (self.auth, hid))
            doc = minidom.parse(data)

            text = doc.getElementsByTagName('text')[0].childNodes[0].nodeValue.encode('utf-8')

            text += "\n\n"+_("<i>Fetched from www.leoslyrics.com</i>")
            return text
        except:
            print(sys.exc_info())
            return ''

